﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DECOR.BL.BE;
using DECOR.BL.BC;
using System.Xml.Linq;
using System.IO;
using System.Configuration;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace DECOR.WinAppFotos
{
    public partial class frmImagenes : Form
    {

        public frmImagenes()
        {
            InitializeComponent();
        }

        private void BuscaMaterial()
        {
            List<MaterialBE> dtMateriales = MaterialBC.Instance.buscarMateriales(txtCodMaterialAntiguo.Text, txtDescMaterial.Text, "");
            grvMaterial.DataSource = dtMateriales;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            grvMaterial.AutoGenerateColumns = false;
            List<MaterialBE> dt = MaterialBC.Instance.buscarMateriales("");
            grvMaterial.DataSource = dt;
        }

        private void grvMaterial_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (grvMaterial.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex != -1 && this.grvMaterial.Columns[e.ColumnIndex].Name == "AgregarImagen" )
            {
                Form ventana = new frmCarga(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.Rows[e.RowIndex].Cells["CodMaterial"].Value.ToString() + ".jpg", grvMaterial.Rows[e.RowIndex].Cells["CodMaterial"].Value.ToString());
                pictureBox1.Image = Image.FromFile(ParametroBC.Instance.getParamValue("RutaImgDefecto"));
                ventana.ShowDialog();
            }

            if (grvMaterial.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex != -1 && this.grvMaterial.Columns[e.ColumnIndex].Name == "BorrarImagen" && File.Exists(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.Rows[e.RowIndex].Cells["CodMaterial"].Value.ToString() + ".jpg"))
            {
                DialogResult resultado = MessageBox.Show("Borrar la imagen?", "Borrar", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
               if (resultado == DialogResult.Yes) {
                   if (File.Exists(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.Rows[e.RowIndex].Cells["CodMaterial"].Value.ToString() + ".jpg"))
                   {
                       //ms.Close();
                       GC.Collect();
                       GC.WaitForPendingFinalizers();
                       File.Delete(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.Rows[e.RowIndex].Cells["CodMaterial"].Value.ToString() + ".jpg");
                       // gh.CopyTo(ParametroBC.Instance.getParamValue("RutaLecturaImg") + @"\" + saverut);
                       pictureBox1.Image = Image.FromFile(ParametroBC.Instance.getParamValue("RutaImgDefecto"));
                   }
               }
            }
        }

        private void grvMaterial_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (grvMaterial.SelectedRows.Count > 0)
                {
                    if (File.Exists(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.SelectedRows[0].Cells["CodMaterial"].Value.ToString() + ".jpg"))
                    {
                        Image imageres = Image.FromFile(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.SelectedRows[0].Cells["CodMaterial"].Value.ToString() + ".jpg");
                        MemoryStream ms2 = new MemoryStream();
                        imageres.Save(ms2, imageres.RawFormat);
                        RescalarImgvista(ms2, imageres);
                    }
                    else
                    {
                        pictureBox1.Image = Image.FromFile(ParametroBC.Instance.getParamValue("RutaImgDefecto"));
                    }
                }
            }
            catch { }
        }

        private void RescalarImgvista(MemoryStream gr, Image imagen2)
        {
            if (imagen2.Height > 200 || imagen2.Width > 200)
            {
                MemoryStream rs2 = ResizeImageFile(gr, 200, 200);
                pictureBox1.Image = Image.FromStream(rs2);
            }
            else
            {
                pictureBox1.Image = Image.FromStream(gr);
            }
        }
        public static MemoryStream ResizeImageFile(MemoryStream imageFile, int targetSizeH, int targetSizeW)
        {
            Image original = Image.FromStream(imageFile);
            int targetH, targetW;
            if (original.Height > original.Width)
            {
                targetH = targetSizeH;
                targetW = (int)(original.Width * ((float)targetSizeH / (float)original.Height));
            }
            else
            {
                targetW = targetSizeW;
                targetH = (int)(original.Height * ((float)targetSizeW / (float)original.Width));
            }
            Image imgPhoto = Image.FromStream(imageFile);

            Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format32bppRgb);
            int calidad = Convert.ToInt32(ParametroBC.Instance.getParamValue("CalidadImg"));
            bmPhoto.SetResolution(calidad, calidad);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
            grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);

            MemoryStream mm = new MemoryStream();
            bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
            original.Dispose();
            imgPhoto.Dispose();
            bmPhoto.Dispose();
            grPhoto.Dispose();

            return mm;
        }

        private void txtCodigoMaterial_TextChanged(object sender, EventArgs e)
        {
            if (txtCodigoMaterial.Text == string.Empty)
            {
                this.BuscaMaterial();
            }
            else
            {
                List<MaterialBE> dt = new List<MaterialBE>();
                MaterialBE itm = MaterialBC.Instance.leerMaterial(txtCodigoMaterial.Text);
                if (itm != null)
                {
                    dt.Add(itm);
                }
                grvMaterial.DataSource = dt;
            }
        }

        private void txtDescMaterial_TextChanged(object sender, EventArgs e)
        {
            this.BuscaMaterial();
        }

        private void frmImagenes_Activated(object sender, EventArgs e)
        {
            try
            {
                if (grvMaterial.SelectedRows.Count > 0)
                {
                    if (File.Exists(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.SelectedRows[0].Cells["CodMaterial"].Value.ToString() + ".jpg"))
                    {
                        Image imageres = Image.FromFile(ParametroBC.Instance.getParamValue("RutaLecturaImg") + grvMaterial.SelectedRows[0].Cells["CodMaterial"].Value.ToString() + ".jpg");
                        MemoryStream ms2 = new MemoryStream();
                        imageres.Save(ms2, imageres.RawFormat);
                        RescalarImgvista(ms2, imageres);
                    }
                    else
                    {
                        pictureBox1.Image = Image.FromFile(ParametroBC.Instance.getParamValue("RutaImgDefecto"));
                    }
                }
            }
            catch { }
        }

        
    }        
}
     


    

